import { Common, areaTree } from 'cby.assist'

// 是否进行字典化
let isDict = true

/**
 * 地区
 */
export default {
  state: {
    area: areaTree
  },
  getters: {
    getArea: state => state.area, // 获取地区
    areaDict: state => {
      // 获取地区字典
      if (isDict) {
        isDict = false
        const valueDict = (list) => {
          list.forEach(item => {
            item.label = item.name
            item.value = item.id
            if (item.children && item.children.length) {
              valueDict(item.children)
            }
          })
        }
        valueDict(state.area)
      }
      return state.area
    },
    getAreaItem: state => areaId =>
      Common.recursiveQuery(areaId, state.area, 'id'), // 获取地区项
    getAreaName: (state, getters) => areaId => {
      // 获取地区名称
      const area = getters.getAreaItem(areaId)
      return area ? area.name : areaId
    }
  }
}
